import { baseUrl } from './config'

const RequestUtil = {
  get(url, params, fun) {
    const token = wx.getStorageSync('token');
    const faUnicode = wx.getStorageSync('unicode');
    let joinParams = '';

    if (params == null || params == undefined) {
      params = {};
    }

    params.faUnicode = faUnicode;
    let temp = '';
    for (let key in params) {
      temp += `${key}=${params[key]}&`
    }
    joinParams = temp.substr(0, temp.length - 1)
    url += '?' + joinParams;

    wx.request({
      url: baseUrl + url,
      method: "GET",
      header: {
        'Authorization': `Bearer ${token}`
      },
      success({ data: { code, data, msg } }) {
        if (code == 0) {
          if (fun) {
            fun(data);
          }
        } else {
          wx.showToast({
            title: msg,
            icon: 'error',
            duration: 2000
          });
          console.log(`${url}请求失败: ${msg}`)
        }
      }, fail({ errMsg }) {
        wx.showToast({
          title: errMsg,
          icon: 'error',
          duration: 2000
        });
        console.log(`${url}请求失败: ${errMsg}`)
      }
    })
  },
  post(url, data, fun) {
    const token = wx.getStorageSync('token');
    wx.request({
      url: baseUrl + url,
      data,
      method: "POST",
      header: {
        'Authorization': `Bearer ${token}`
      },
      success({ data: { code, data, msg } }) {
        if (code == 0) {
          if (fun) {
            fun(data);
          }
        } else {
          wx.showToast({
            title: msg,
            icon: 'error',
            duration: 2000
          });
          console.log(`${url}请求失败: ${msg}`)
        }
      }, fail({ errMsg }) {
        wx.showToast({
          title: errMsg,
          icon: 'error',
          duration: 2000
        });
        console.log(`${url}请求失败: ${errMsg}`)
      }
    })
  },
  download(url, params, fun) {
    const token = wx.getStorageSync('token');
    const faUnicode = wx.getStorageSync('unicode');
    let joinParams = '';

    if (params == null || params == undefined) {
      params = {};
    }

    params.faUnicode = faUnicode;
    let temp = '';
    for (let key in params) {
      temp += `${key}=${params[key]}&`
    }
    joinParams = temp.substr(0, temp.length - 1)
    url += '?' + joinParams;

    wx.downloadFile({
      url: baseUrl + url,
      header: {
        'Authorization': `Bearer ${token}`
      },
      success({ tempFilePath, statusCode }) {
        if (statusCode === 200) {
          if (fun) {
            fun({
              filePath: tempFilePath
            })
          }
        }
      },
      fail(error) {
        console.log(error)
        wx.showToast({
          title: '下载失败',
          icon: 'error',
          duration: 2000
        });
      }
    })
  },


}

module.exports = {
  ...RequestUtil
}